package com.yst.feign1.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yst.feign1.config.BodyReaderHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class LogHandlerInterceptor implements HandlerInterceptor, Ordered {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LogHandlerInterceptor");
        if (!(request instanceof BodyReaderHttpServletRequestWrapper)) {
            System.out.println("not replace request");
            return true;
        }
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String param = Optional.ofNullable(request.getParameterMap()).map(JSONObject::toJSONString).orElse(null);
        String body = "";
        try (ServletInputStream sis = request.getInputStream();
             InputStreamReader isr = new InputStreamReader(sis, "UTF-8");
             BufferedReader br = new BufferedReader(isr)
        ) {
            body = br.lines().collect(Collectors.joining());
        } catch (Exception e) {
            log.warn("读取请求体数据失败");
        }
        Map<String, String> map = new HashMap<>();
        map.put("method", method);
        map.put("uri", uri);
        map.put("param", param);
        map.put("body", body);
        log.info("请求参数" + JSONObject.toJSONString(map));
        return true;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
